import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { CodeViewerData, CodeRegion, CodeFileContent } from '../models/code-content.interface';

@Injectable({
  providedIn: 'root'
})
export class CodeDataService {

  constructor() { }

  // 模拟获取代码数据
  getCodeData(): Observable<CodeViewerData> {
    // 使用简化的TypeScript代码示例，避免模板字符串问题
    const codeContent = [
      "import { Component, OnInit, OnDestroy, ViewChild, ElementRef, AfterViewInit } from '@angular/core';",
      "import { CommonModule } from '@angular/common';",
      "import { DomSanitizer, SafeHtml } from '@angular/platform-browser';",
      "import { Observable, Subject, BehaviorSubject, combineLatest } from 'rxjs';",
      "import { map, takeUntil, debounceTime, distinctUntilChanged, filter } from 'rxjs/operators';",
      "import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';",
      "import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';",
      "",
      "// 接口定义",
      "interface UserData {",
      "  id: number;",
      "  name: string;",
      "  email: string;",
      "  role: 'admin' | 'user' | 'guest';",
      "  preferences: UserPreferences;",
      "  lastLoginAt: Date;",
      "}",
      "",
      "interface UserPreferences {",
      "  theme: 'light' | 'dark' | 'auto';",
      "  language: string;",
      "  notifications: {",
      "    email: boolean;",
      "    push: boolean;",
      "    sms: boolean;",
      "  };",
      "  dashboard: {",
      "    layout: 'grid' | 'list';",
      "    itemsPerPage: number;",
      "    autoRefresh: boolean;",
      "  };",
      "}",
      "",
      "// 类型别名",
      "type ApiResponse<T> = {",
      "  success: boolean;",
      "  data: T;",
      "  message?: string;",
      "  timestamp: number;",
      "};",
      "",
      "type EventCallback<T = any> = (data: T) => void;",
      "",
      "// 枚举",
      "enum UserStatus {",
      "  ACTIVE = 'active',",
      "  INACTIVE = 'inactive',",
      "  PENDING = 'pending',",
      "  SUSPENDED = 'suspended'",
      "}",
      "",
      "enum HttpMethod {",
      "  GET = 'GET',",
      "  POST = 'POST',",
      "  PUT = 'PUT',",
      "  DELETE = 'DELETE',",
      "  PATCH = 'PATCH'",
      "}",
      "",
      "/**",
      " * 用户管理组件",
      " * 负责用户数据的展示、编辑和管理",
      " */",
      "@Component({",
      "  selector: 'app-user-manager',",
      "  standalone: true,",
      "  imports: [CommonModule],",
      "  templateUrl: './user-manager.component.html',",
      "  styleUrls: ['./user-manager.component.scss']",
      "})",
      "export class UserManagerComponent implements OnInit, OnDestroy, AfterViewInit {",
      "  @ViewChild('userTable', { static: false }) userTable!: ElementRef<HTMLTableElement>;",
      "  @ViewChild('searchInput', { static: false }) searchInput!: ElementRef<HTMLInputElement>;",
      "",
      "  // 数据状态",
      "  users: UserData[] = [];",
      "  filteredUsers: UserData[] = [];",
      "  selectedUsers: Set<number> = new Set();",
      "  loading = false;",
      "  error: string | null = null;",
      "",
      "  // UI状态",
      "  currentPage = 1;",
      "  itemsPerPage = 10;",
      "  totalPages = 0;",
      "  showFilters = false;",
      "  sortColumn: keyof UserData | null = null;",
      "  sortDirection: 'asc' | 'desc' = 'asc';",
      "",
      "  // 搜索和过滤",
      "  private searchSubject = new BehaviorSubject<string>('');",
      "  private filterSubject = new BehaviorSubject<any>({});",
      "  private destroy$ = new Subject<void>();",
      "",
      "  // 表单状态",
      "  editingUser: UserData | null = null;",
      "  showUserModal = false;",
      "  userForm: any = null;",
      "",
      "  constructor(",
      "    private http: HttpClient,",
      "    private router: Router,",
      "    private route: ActivatedRoute,",
      "    private sanitizer: DomSanitizer",
      "  ) {}",
      "",
      "  ngOnInit(): void {",
      "    this.initializeComponent();",
      "    this.setupSearchAndFilter();",
      "    this.loadUsers();",
      "  }",
      "",
      "  ngAfterViewInit(): void {",
      "    this.setupTableInteractions();",
      "    this.initializeSearchInput();",
      "  }",
      "",
      "  ngOnDestroy(): void {",
      "    this.destroy$.next();",
      "    this.destroy$.complete();",
      "  }",
      "",
      "  /**",
      "   * 初始化组件",
      "   */",
      "  private initializeComponent(): void {",
      "    console.log('初始化用户管理组件');",
      "",
      "    // 监听路由参数变化",
      "    this.route.queryParams",
      "      .pipe(takeUntil(this.destroy$))",
      "      .subscribe(params => {",
      "        if (params['page']) {",
      "          this.currentPage = parseInt(params['page'], 10);",
      "        }",
      "        if (params['search']) {",
      "          this.searchSubject.next(params['search']);",
      "        }",
      "      });",
      "",
      "    // 监听导航事件",
      "    this.router.events",
      "      .pipe(",
      "        filter(event => event instanceof NavigationEnd),",
      "        takeUntil(this.destroy$)",
      "      )",
      "      .subscribe(() => {",
      "        console.log('导航完成，刷新数据');",
      "        this.loadUsers();",
      "      });",
      "  }",
      "",
      "  /**",
      "   * 设置搜索和过滤功能",
      "   */",
      "  private setupSearchAndFilter(): void {",
      "    // 搜索功能",
      "    const search$ = this.searchSubject.pipe(",
      "      debounceTime(300),",
      "      distinctUntilChanged()",
      "    );",
      "",
      "    // 过滤功能",
      "    const filter$ = this.filterSubject.pipe(",
      "      distinctUntilChanged()",
      "    );",
      "",
      "    // 合并搜索和过滤",
      "    combineLatest([search$, filter$])",
      "      .pipe(",
      "        takeUntil(this.destroy$),",
      "        map(([searchTerm, filters]) => ({ searchTerm, filters }))",
      "      )",
      "      .subscribe(({ searchTerm, filters }) => {",
      "        this.applySearchAndFilter(searchTerm, filters);",
      "      });",
      "  }",
      "",
      "  /**",
      "   * 应用搜索和过滤",
      "   */",
      "  private applySearchAndFilter(searchTerm: string, filters: any): void {",
      "    let filtered = [...this.users];",
      "",
      "    // 应用搜索",
      "    if (searchTerm.trim()) {",
      "      const term = searchTerm.toLowerCase();",
      "      filtered = filtered.filter(user =>",
      "        user.name.toLowerCase().includes(term) ||",
      "        user.email.toLowerCase().includes(term) ||",
      "        user.role.toLowerCase().includes(term)",
      "      );",
      "    }",
      "",
      "    // 应用过滤器",
      "    if (filters.role && filters.role !== 'all') {",
      "      filtered = filtered.filter(user => user.role === filters.role);",
      "    }",
      "",
      "    // 应用排序",
      "    if (this.sortColumn) {",
      "      filtered = this.sortUsers(filtered, this.sortColumn, this.sortDirection);",
      "    }",
      "",
      "    this.filteredUsers = filtered;",
      "    this.calculatePagination();",
      "    this.currentPage = 1;",
      "  }",
      "",
      "  /**",
      "   * 加载用户数据",
      "   */",
      "  private async loadUsers(): Promise<void> {",
      "    this.loading = true;",
      "    this.error = null;",
      "",
      "    try {",
      "      const headers = new HttpHeaders({",
      "        'Content-Type': 'application/json',",
      "        'Authorization': 'Bearer ' + this.getAuthToken()",
      "      });",
      "",
      "      const params = new HttpParams()",
      "        .set('page', this.currentPage.toString())",
      "        .set('limit', this.itemsPerPage.toString());",
      "",
      "      const response = await this.http.get('/api/users', { headers, params }).toPromise();",
      "",
      "      if (response) {",
      "        this.users = response as UserData[];",
      "        this.filteredUsers = [...this.users];",
      "        this.calculatePagination();",
      "        console.log('加载了用户数据');",
      "      }",
      "    } catch (error) {",
      "      console.error('加载用户数据失败:', error);",
      "      this.error = '无法加载用户数据，请稍后重试';",
      "      this.loadMockUsers();",
      "    } finally {",
      "      this.loading = false;",
      "    }",
      "  }",
      "",
      "  /**",
      "   * 加载模拟用户数据",
      "   */",
      "  private loadMockUsers(): void {",
      "    console.log('使用模拟数据');",
      "",
      "    this.users = [",
      "      {",
      "        id: 1,",
      "        name: '张三',",
      "        email: 'zhangsan@example.com',",
      "        role: 'admin',",
      "        preferences: {",
      "          theme: 'light',",
      "          language: 'zh-CN',",
      "          notifications: { email: true, push: true, sms: false },",
      "          dashboard: { layout: 'grid', itemsPerPage: 20, autoRefresh: true }",
      "        },",
      "        lastLoginAt: new Date('2024-01-15T10:30:00')",
      "      },",
      "      {",
      "        id: 2,",
      "        name: '李四',",
      "        email: 'lisi@example.com',",
      "        role: 'user',",
      "        preferences: {",
      "          theme: 'dark',",
      "          language: 'zh-CN',",
      "          notifications: { email: true, push: false, sms: true },",
      "          dashboard: { layout: 'list', itemsPerPage: 10, autoRefresh: false }",
      "        },",
      "        lastLoginAt: new Date('2024-01-14T16:45:00')",
      "      }",
      "    ];",
      "",
      "    this.filteredUsers = [...this.users];",
      "    this.calculatePagination();",
      "  }",
      "",
      "  /**",
      "   * 排序用户数据",
      "   */",
      "  private sortUsers(users: UserData[], column: keyof UserData, direction: 'asc' | 'desc'): UserData[] {",
      "    return users.sort((a, b) => {",
      "      const aValue = a[column];",
      "      const bValue = b[column];",
      "",
      "      let comparison = 0;",
      "",
      "      if (aValue < bValue) {",
      "        comparison = -1;",
      "      } else if (aValue > bValue) {",
      "        comparison = 1;",
      "      }",
      "",
      "      return direction === 'desc' ? -comparison : comparison;",
      "    });",
      "  }",
      "",
      "  /**",
      "   * 计算分页信息",
      "   */",
      "  private calculatePagination(): void {",
      "    this.totalPages = Math.ceil(this.filteredUsers.length / this.itemsPerPage);",
      "",
      "    if (this.currentPage > this.totalPages) {",
      "      this.currentPage = Math.max(1, this.totalPages);",
      "    }",
      "  }",
      "",
      "  /**",
      "   * 获取认证令牌",
      "   */",
      "  private getAuthToken(): string {",
      "    return localStorage.getItem('auth_token') || '';",
      "  }",
      "",
      "  /**",
      "   * 删除用户",
      "   */",
      "  async deleteUser(userId: number): Promise<void> {",
      "    const confirmed = confirm('确定要删除这个用户吗？');",
      "    if (!confirmed) return;",
      "",
      "    try {",
      "      await this.http.delete('/api/users/' + userId).toPromise();",
      "      this.users = this.users.filter(user => user.id !== userId);",
      "      this.applySearchAndFilter(this.searchSubject.value, this.filterSubject.value);",
      "      console.log('用户已删除');",
      "    } catch (error) {",
      "      console.error('删除用户失败:', error);",
      "      alert('删除用户失败，请稍后重试');",
      "    }",
      "  }",
      "",
      "  /**",
      "   * 页面导航",
      "   */",
      "  goToPage(page: number): void {",
      "    if (page >= 1 && page <= this.totalPages) {",
      "      this.currentPage = page;",
      "      this.router.navigate([], {",
      "        relativeTo: this.route,",
      "        queryParams: { page },",
      "        queryParamsHandling: 'merge'",
      "      });",
      "    }",
      "  }",
      "",
      "  /**",
      "   * 切换排序",
      "   */",
      "  toggleSort(column: keyof UserData): void {",
      "    if (this.sortColumn === column) {",
      "      this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';",
      "    } else {",
      "      this.sortColumn = column;",
      "      this.sortDirection = 'asc';",
      "    }",
      "",
      "    this.applySearchAndFilter(this.searchSubject.value, this.filterSubject.value);",
      "  }",
      "",
      "  /**",
      "   * 获取分页信息文本",
      "   */",
      "  getPaginationInfo(): string {",
      "    const start = (this.currentPage - 1) * this.itemsPerPage + 1;",
      "    const end = Math.min(this.currentPage * this.itemsPerPage, this.filteredUsers.length);",
      "    return '显示 ' + start + '-' + end + ' 项，共 ' + this.filteredUsers.length + ' 项';",
      "  }",
      "",
      "  /**",
      "   * 导出用户数据",
      "   */",
      "  exportUsers(): void {",
      "    const csvContent = this.generateCSV(this.filteredUsers);",
      "    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });",
      "    const link = document.createElement('a');",
      "    const url = URL.createObjectURL(blob);",
      "",
      "    link.setAttribute('href', url);",
      "    link.setAttribute('download', 'users.csv');",
      "    link.style.visibility = 'hidden';",
      "    document.body.appendChild(link);",
      "    link.click();",
      "    document.body.removeChild(link);",
      "  }",
      "",
      "  /**",
      "   * 生成CSV内容",
      "   */",
      "  private generateCSV(users: UserData[]): string {",
      "    const headers = ['ID', '姓名', '邮箱', '角色', '最后登录时间'];",
      "    const rows = users.map(user => [",
      "      user.id.toString(),",
      "      user.name,",
      "      user.email,",
      "      user.role,",
      "      user.lastLoginAt.toLocaleDateString()",
      "    ]);",
      "",
      "    const csvArray = [headers, ...rows];",
      "    return csvArray.map(row => row.join(',')).join('\\n');",
      "  }",
      "}",
      "",
      "// 工具函数",
      "export function formatUserRole(role: string): string {",
      "  const roleMap: Record<string, string> = {",
      "    'admin': '管理员',",
      "    'user': '普通用户',",
      "    'guest': '访客'",
      "  };",
      "  return roleMap[role] || role;",
      "}",
      "",
      "export function formatDateTime(date: Date): string {",
      "  return new Intl.DateTimeFormat('zh-CN', {",
      "    year: 'numeric',",
      "    month: '2-digit',",
      "    day: '2-digit',",
      "    hour: '2-digit',",
      "    minute: '2-digit',",
      "    second: '2-digit'",
      "  }).format(date);",
      "}",
      "",
      "// 工具类",
      "export class UserValidator {",
      "  static validateEmail(email: string): boolean {",
      "    const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;",
      "    return emailRegex.test(email);",
      "  }",
      "",
      "  static validateName(name: string): boolean {",
      "    return name.trim().length >= 2 && name.trim().length <= 50;",
      "  }",
      "",
      "  static validateRole(role: string): boolean {",
      "    return ['admin', 'user', 'guest'].includes(role);",
      "  }",
      "}",
      "",
      "// 常量",
      "export const USER_ROLES = {",
      "  ADMIN: 'admin' as const,",
      "  USER: 'user' as const,",
      "  GUEST: 'guest' as const",
      "};",
      "",
      "export const DEFAULT_USER_PREFERENCES: UserPreferences = {",
      "  theme: 'light',",
      "  language: 'zh-CN',",
      "  notifications: {",
      "    email: true,",
      "    push: true,",
      "    sms: false",
      "  },",
      "  dashboard: {",
      "    layout: 'grid',",
      "    itemsPerPage: 10,",
      "    autoRefresh: false",
      "  }",
      "};"
    ].join('\n');

    const mockFileContent: CodeFileContent = {
      content: codeContent,
      language: 'typescript',
      filename: 'user-manager.component.ts',
      totalLines: 456
    };

    const mockVisibleRegions: CodeRegion[] = [
      { 
        startLine: 1, 
        endLine: 7, 
        id: 'imports',
        backgroundColor: '#e3f2fd' // 淡蓝色背景 - 导入区域
      },
      { 
        startLine: 9, 
        endLine: 47, 
        id: 'interfaces',
        backgroundColor: '#f3e5f5' // 淡紫色背景 - 接口定义
      },
      { 
        startLine: 57, 
        endLine: 75, 
        id: 'component-decorator',
        backgroundColor: '#e8f5e8' // 淡绿色背景 - 组件装饰器
      },
      { 
        startLine: 76, 
        endLine: 95, 
        id: 'component-properties',
        backgroundColor: '#fff3e0' // 淡橙色背景 - 组件属性
      },
      { 
        startLine: 97, 
        endLine: 115, 
        id: 'constructor-lifecycle',
        backgroundColor: '#fce4ec' // 淡粉色背景 - 构造函数和生命周期
      },
      { 
        startLine: 200, 
        endLine: 230, 
        id: 'load-users-method',
        backgroundColor: '#e0f2f1' // 淡青色背景 - 加载用户方法
      },
      { 
        startLine: 350, 
        endLine: 375, 
        id: 'pagination-methods',
        backgroundColor: '#f1f8e9' // 淡绿色背景 - 分页方法
      },
      { 
        startLine: 420, 
        endLine: 456, 
        id: 'utility-exports',
        backgroundColor: '#fafafa' // 浅灰色背景 - 工具函数和常量
      }
    ];

    const mockData: CodeViewerData = {
      fileContent: mockFileContent,
      visibleRegions: mockVisibleRegions
    };

    return of(mockData);
  }

  // 获取更多代码内容（用于展开功能）
  getExpandedContent(startLine: number, endLine: number): Observable<string> {
    // 模拟获取更多内容
    const additionalLines = [];
    for (let i = startLine; i <= endLine; i++) {
      additionalLines.push(`  // 第 ${i} 行的额外代码内容`);
    }
    
    return of(additionalLines.join('\n'));
  }
} 